package com.my.controller;

import com.my.utils.AliOSSProperties;
import com.my.entity.Result;
import com.my.utils.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
public class UploadController {
    /**
     * 文件上传 - 本地存储


    @PostMapping("/upload")
    public Result upload(String username, Integer age, MultipartFile file) throws Exception {
        log.info("参数：{},{},{}", username, age, file);
        // 1.获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 2. 截取后缀
        String newFileName  = UUID.randomUUID()  + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 2.将前端上传的文件下载到本地
        file.transferTo(new File("D:" + newFileName));

        return Result.success(newFileName);
    }     */

//    private final String bucketName = "bucket-25-9-23"; //oss上的桶名
//    private final String endpoint = "https://oss-cn-beijing.aliyuncs.com";// 桶对应的域名
    /** 配置文件定义变量
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;//oss上桶对应的域名
    @Value("${aliyun.oss.bucket}")
    private String bucketName;  //oss上的桶名
    */

    /** 配置类配置 变量 */
    @Autowired
    private AliOSSProperties aOSSProperties;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        // 1.获得名字后缀
        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("原始名字:{}", originalFilename);

        // 2.调用阿里云OSS工具类，将文件上传到OSS
        String url = AliyunOSSUtils.upload(aOSSProperties.getEndpoint(), aOSSProperties.getBucket(), file.getBytes(), ext);

        return Result.success(url);
    }
}
